﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;

namespace TiaoTiaoCode.AutoUpdate.WebApi.StartUps
{
    /// <summary>
    /// JWT启动
    /// </summary>
    public static class JwtStartup
    {
        /// <summary>
        /// 添加JWT启动
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddJwtStartup(this IServiceCollection services, IConfiguration configuration)
        {            
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>
                    {
                        var cfg = configuration.GetSection("JWT");
                        opt.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidIssuer = cfg["Issuer"],
                            ValidateAudience = true,
                            ValidAudience = cfg["audience"],
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cfg["SecurityKey"]))
                        };
                    });


            services.AddCors(options =>
            {
                options.AddPolicy("Any",
                    builder => builder.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .Build());
            });
        }
    }
}
